'use strict';

module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const AuthPageSchema = new Schema({
    /**
     * 标题
     */
    title: { type: String, default: '' },
    /**
     * 图标
     */
    icon: { type: String, default: '' },
    /**
     * 索引，用来排序
     */
    index: { type: Number, default: 0, min: 0, max: 9 },
    /**
     * 类型，文件夹/子文件夹/文件
     */
    type: { type: String, default: 'FOLDER', enum: [ 'FOLDER', 'SUB_FOLDER', 'FILE' ] },
    /**
     * 路径
     */
    path: { type: String, default: '' },
    /**
     * 子对象
     */
    children: [{ type: Schema.Types.ObjectId, ref: 'AuthPage' }],
    /**
     * 描述
     */
    describe: { type: String, default: '' },
  });

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 获取所有界面
   */
  AuthPageSchema.statics.findAll = function() {
    const model = this.find({
      type: 'FOLDER',
    });
    model.populate({
      path: 'children',
      populate: { path: 'children' },
    });
    return model.sort({ index: 1 }).exec();
  };

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 查询单个数据
   */
  AuthPageSchema.statics.findWithId = async function(id) {
    return this.findOne({
      _id: mongoose.Types.ObjectId(id),
    });
  };

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 修改数据
   */
  AuthPageSchema.statics.updateWithId = function(id, data) {
    return this.updateOne({
      _id: mongoose.Types.ObjectId(id),
    }, data);
  };

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 删除数据
   */
  AuthPageSchema.statics.removeWithId = async function(id) {
    // 删除父节点里面的数据
    await this.updateOne({ children: { $elemMatch: { $eq: mongoose.Types.ObjectId(id) } } }, {
      $pull: {
        children: mongoose.Types.ObjectId(id),
      },
    });
    // 删除子节点
    return this.deleteOne({
      _id: mongoose.Types.ObjectId(id),
    });
  };

  // eslint-disable-next-line jsdoc/require-param
  /**
   * 添加子节点
   */
  AuthPageSchema.statics.addSubNode = async function(id, subId) {
    return this.updateOne({
      _id: mongoose.Types.ObjectId(id),
    }, {
      $push: {
        children: mongoose.Types.ObjectId(subId),
      },
    });
  };

  return mongoose.model('AuthPage', AuthPageSchema, 'authPage');
};
